package cn.net.ecode.elec.api.web;

import cn.net.ecode.annotation.Login;
import cn.net.ecode.annotation.LoginUser;
import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.utils.JedisUtils;
import cn.net.ecode.common.utils.StringUtils;
import cn.net.ecode.common.web.BaseController;
import cn.net.ecode.constant.LoginTypeEnum;
import cn.net.ecode.constant.SendSmsTypeEnum;
import cn.net.ecode.elec.api.entity.LoginForm;
import cn.net.ecode.elec.api.entity.SubAdminForm;
import cn.net.ecode.elec.api.service.ElecUserService;
import cn.net.ecode.mdm.entity.MdmBtypeInfo;
import cn.net.ecode.modules.sys.entity.User;
import cn.net.ecode.modules.sys.service.UserService;
import cn.net.ecode.util.FileUploadUtils;
import cn.net.ecode.util.JwtUtils;
import cn.net.ecode.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName AppUserController
 * @Description 用户注册接口
 * @Author AlanShelby
 * @Date 2019/8/27 0027 8:43
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/admin")
public class AppUserController extends BaseController {

    @Autowired
    private ElecUserService elecUserService;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * @Method login
     * @Description 登录接口
     * @Author AlanShelby
     * @Date 8:53 2019/8/29 0029
     * @Param [loginForm]
     * @Return cn.net.ecode.util.R
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public R login(@RequestBody LoginForm loginForm) {
        // 表单校验
        StringBuilder message = new StringBuilder();
        if (!beanValidator(message, loginForm)) {
            return R.error(message.toString());
        }

        User user = new User();
        user.setLoginCode(loginForm.getPhone());
        user = userService.getByLoginCode(user);
        if (user == null) {
            return R.error("用户手机号错误，无法找到该用户");
        }

        // 不同登录方式校验
        Map<String, Object> map = new HashMap<>();
        if (loginForm.getLoginType() == LoginTypeEnum.PASSWORD.getCode()) {
            // 密码登录
            boolean isLogin = UserService.validatePassword(loginForm.getPassword(), user.getPassword());
            if (!isLogin) {
                return R.error("登录失败，密码不正确");
            }

            //生成token
            String token = jwtUtils.generateToken(user.getUserCode());
            map.put("token", token);
            map.put("expire", jwtUtils.getExpire());
        } else if (loginForm.getLoginType() == LoginTypeEnum.VALIDATE_CODE.getCode()) {
            // 短信验证码登录
            String generateKey = JedisUtils.KEY_PREFIX + ":" + SendSmsTypeEnum.LOGIN.getCode() + ":" + loginForm.getPhone();

            String validateCode = JedisUtils.get(generateKey);
            if (validateCode == null) {
                return R.error("验证码不存在或已过期");
            }

            if (StringUtils.equals(loginForm.getValidateCode(), validateCode)) {
                //生成token
                String token = jwtUtils.generateToken(user.getUserCode());
                map.put("token", token);
                map.put("expire", jwtUtils.getExpire());
                // 清除验证码
                JedisUtils.del(generateKey);
            } else {
                return R.error("验证码不匹配");
            }
        } else {
            return R.error("登录类型有误，请联系管理员");
        }

        return R.ok(map);
    }

    /**
     * @Method registerAdmin
     * @Description 管理员注册
     * @Author AlanShelby
     * @Date 8:45 2019/8/27 0027
     * @Param [type]
     * @Return cn.net.ecode.util.R
     */
    @RequestMapping(value = "/registerAdmin", method = RequestMethod.POST)
    public R registerAdmin(@RequestBody MdmBtypeInfo mdmBtypeInfo) {
        StringBuilder message = new StringBuilder();
        if (!beanValidator(message, mdmBtypeInfo)) {
            return R.error(message.toString());
        }

        // 校验验证码
        String generateKey = JedisUtils.KEY_PREFIX + ":" + SendSmsTypeEnum.REGISTER.getCode() + ":" + mdmBtypeInfo.getLinkmanTel();
        String validateCode = JedisUtils.get(generateKey);
        if (validateCode == null) {
            return R.error("验证码不存在或已过期");
        }

        if (StringUtils.equals(mdmBtypeInfo.getValidateCode(), validateCode)) {
            elecUserService.registerAdmin(mdmBtypeInfo);

            // 清除验证码
            JedisUtils.del(generateKey);
        } else {
            return R.error("验证码不匹配");
        }

        return R.ok();
    }

    /**
     * @Method uploadEnterpriseImage
     * @Description 上传企业图片
     * @Author AlanShelby
     * @Date 14:33 2019/8/27 0027
     * @Param [files]
     * @Return cn.net.ecode.util.R
     */
    @RequestMapping(value = "/uploadEnterpriseImage", method = RequestMethod.POST)
    public R uploadEnterpriseImage(@RequestParam(value = "files", required = true) MultipartFile[] files) {
        String basePath = Global.getConfig("userfiles.basedir");
        StringBuilder imageUrls = new StringBuilder();
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                String imageUrl;
                try {
                    imageUrl = FileUploadUtils.fileUpload(file, basePath, "image/enterprise");
                } catch (IOException e) {
                    e.printStackTrace();
                    return R.error("文件上传出错");
                }
                if (files.length == (i + 1)) {
                    imageUrls.append(imageUrl);
                } else {
                    imageUrls.append(imageUrl).append("|");
                }
            }
        }

        return R.ok().put("imageUrls", imageUrls);
    }

    /**
     * @Method allotSubAdmin
     * @Description 子管理员分配
     * @Author AlanShelby
     * @Date 8:45 2019/8/27 0027
     * @Param [type]
     * @Return cn.net.ecode.util.R
     */
    @Login
    @RequestMapping(value = "/allotSubAdmin", method = RequestMethod.POST)
    public R allotSubAdmin(@RequestBody SubAdminForm subAdminForm) {
        StringBuilder message = new StringBuilder();
        if (!beanValidator(message, subAdminForm)) {
            return R.error(message.toString());
        }

        elecUserService.registerSubAdmin(subAdminForm);

        return R.ok();
    }

    /**
     * @Method userInfo
     * @Description 获取用户信息
     * @Author AlanShelby
     * @Date 10:14 2019/8/30 0030
     * @Param [user]
     * @Return cn.net.ecode.util.R
     */
    @Login
    @RequestMapping(value = "userInfo", method = RequestMethod.GET)
    public R userInfo(@LoginUser User user) {

        return R.ok().put("userInfo", user);
    }
}
